package com.swg.cocobox.filetransfer.example;

import java.io.IOException;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.swg.cocobox.filetransfer.ClientCommandDispatcherFactory;
import com.swg.cocobox.filetransfer.ClientCommandDispatcher;
import com.swg.cocobox.filetransfer.CommandDispatcherHelper;
import com.swg.cocobox.filetransfer.FileServer;
import com.swg.cocobox.filetransfer.command.ClientCommand;
import com.swg.cocobox.filetransfer.command.CommandContext;
import com.swg.cocobox.filetransfer.command.CommandEventProcessor;
import com.swg.cocobox.filetransfer.command.CommandEventSupport;
import com.swg.cocobox.filetransfer.command.CommandContext.CommandEncoding;
import com.swg.cocobox.filetransfer.data.DataTransfer;

public class SimpleFileServer extends FileServer{

	private DataTransfer dataTransfer;
	
	private ExecutorService service=Executors.newCachedThreadPool();
	
	public SimpleFileServer(String host, int port) throws IOException {
		super(host, port);
		dataTransfer=new DataTransfer();
		setDataTransfer(dataTransfer);
		setClientCommandFactory(CommandContext.getClientCommandFactory(CommandEncoding.ASCII));
		setEventSupport(new CommandEventSupport(this));
		setEventProcessor(new CommandEventProcessor());
	}
	
	@Override
	public synchronized void startServer() {
		Thread thread=new Thread(this);
		thread.start();
		service.execute(getEventProcessor());
		service.execute(getDataTransfer());
	}
	
	@Override
	protected void handle(SocketChannel channel, ClientCommand command)throws IOException {
		ClientCommandDispatcherFactory dispatcherFactory=CommandDispatcherHelper.getBuiltinDispatcherFactory();
		ClientCommandDispatcher dispatcher=dispatcherFactory.createDispatcher(command);
		dispatcher.dispatch(this, channel, command);
	}

	public static void main(String[] args)throws IOException{
		FileServer server=new SimpleFileServer("127.0.0.1", 1234);
		server.startServer();
	}

}
